package com.jhgsys.internal.base.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jhgsys.internal.base.dto.BaseAreDto;
import com.jhgsys.internal.base.entity.BaseArea;
import com.jhgsys.internal.base.entity.BaseAreaScheduling;
import com.jhgsys.internal.base.service.IBaseAreaSchedulingService;
import com.jhgsys.internal.base.service.IBaseAreaService;
import com.jhgsys.internal.common.annotation.Log;
import com.jhgsys.internal.common.controller.BaseController;
import com.jhgsys.internal.common.entity.FebsConstant;
import com.jhgsys.internal.common.entity.FebsResponse;
import com.jhgsys.internal.common.entity.QueryRequest;
import com.jhgsys.internal.common.exception.FebsException;
import com.jhgsys.internal.common.utils.DateUtil;
import com.jhgsys.internal.common.utils.FebsUtil;
import com.wuwenze.poi.ExcelKit;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 区域设置 Controller
 *
 * @author admin
 * @date 2024-07-31 14:35:47
 */
@Slf4j
@Validated
@Controller
public class BaseAreaController extends BaseController {

    @Autowired
    private IBaseAreaService baseAreaService;

    @Autowired
    private IBaseAreaSchedulingService schedulingService;

    @GetMapping(FebsConstant.VIEW_PREFIX + "baseArea")
    @RequiresPermissions("baseArea:view")
    public String baseAreaIndex(Model model){
        model.addAttribute("tenantList", getTenantList());
        model.addAttribute("tenantId", getCurrentTenantId());
        model.addAttribute("hasHeadCompanyRole", hasHeadCompanyRole());
        return FebsUtil.view("base/baseArea/baseAreaList");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "baseArea/add")
    @RequiresPermissions("baseArea:add")
    public String baseAreaAdd(Model model){
        model.addAttribute("baseArea", new BaseArea());
        return FebsUtil.view("base/baseArea/baseAreaEdit");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "baseArea/update/{id}")
    @RequiresPermissions("baseArea:edit")
    public String baseAreaUpdate(Model model, @PathVariable("id") String  id){
        BaseArea area = baseAreaService.getOne(new LambdaQueryWrapper<BaseArea>().eq(BaseArea::getAreaId,id));
        model.addAttribute("baseArea", area);
        return FebsUtil.view("base/baseArea/baseAreaEdit");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "baseArea/baseAreaEditMap/{id}")
    public String baseAreaEditMap(Model model, @PathVariable("id") String  id){
        BaseArea area = baseAreaService.getOne(new LambdaQueryWrapper<BaseArea>().eq(BaseArea::getAreaId,id));
        model.addAttribute("baseArea", area);
        return FebsUtil.view("base/baseArea/baseAreaEditMap");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "baseArea/baseAreaViewMap/{id}")
    public String baseAreaViewMap(Model model, @PathVariable("id") String  id){
        BaseArea area = baseAreaService.getOne(new LambdaQueryWrapper<BaseArea>().eq(BaseArea::getAreaId,id));
        model.addAttribute("baseArea", area);
        return FebsUtil.view("base/baseArea/baseAreaViewMap");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "baseArea/baseEditMap")
    public String baseEditMap(){
        return FebsUtil.view("base/baseEditMap");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "baseArea/baseViewMap")
    public String baseViewMap(){
        return FebsUtil.view("base/baseViewMap");
    }

    /**
     * 根据areaId 查询区域信息
     * @param model
     * @param id
     * @return
     */
    @GetMapping( "baseArea/get/{id}")
    @ResponseBody
    @RequiresPermissions("baseArea:view")
    public FebsResponse baseAreaById(Model model, @PathVariable("id") String  id){
        return new FebsResponse().success().data(baseAreaService.findBaseAreaById(id));
    }

    /**
     * 查询（所有）
     * @author admin
     * @date 2024-07-31 14:35:47
     */
    @GetMapping("baseArea")
    @ResponseBody
    @RequiresPermissions("baseArea:view")
    public FebsResponse getAllBaseAreas(BaseArea baseArea) {
        return new FebsResponse().success().data(baseAreaService.findBaseAreaList(baseArea));
    }

    /**
     * 查询（分页）
     * @author admin
     * @date 2024-07-31 14:35:47
     */
    @GetMapping("baseArea/list")
    @ResponseBody
    @RequiresPermissions("baseArea:view")
    public FebsResponse baseAreaList(QueryRequest request, BaseAreDto baseArea) {
        if(baseArea.getSchedulingDate() == null){
            baseArea.setSchedulingDate(DateUtil.getCurrentDay());
        }
        Map<String, Object> dataTable = getDataTable(this.baseAreaService.findBaseAreaPage(request, baseArea));
        return new FebsResponse().success().data(dataTable);
    }

    /**
     * 新增 BaseArea
     * @author admin
     * @date 2024-07-31 14:35:47
     */
    @Log("新增区域信息")
    @PostMapping("baseArea")
    @ResponseBody
    @RequiresPermissions("baseArea:add")
    public FebsResponse addBaseArea(@RequestBody  BaseArea baseArea) throws FebsException {
        try {
            if(StringUtils.isBlank(baseArea.getAreaName())){
                return new FebsResponse().fail().message("区域名称不能为空");
            }
            if(StringUtils.isBlank(baseArea.getAreaCoordinate())){
                return new FebsResponse().fail().message("位置信息不能为空");
            }
            if(StringUtils.isBlank(baseArea.getAreaType())){
                return new FebsResponse().fail().message("区域类型不能为空");
            }
            if(StringUtils.isBlank(baseArea.getSort())){
                return new FebsResponse().fail().message("排序不能为空");
            }
            if(StringUtils.isBlank(baseArea.getTenantId())){
                return new FebsResponse().fail().message("所属公司不能为空");
            }

            if(StringUtils.isBlank(baseArea.getStatus())){
                return new FebsResponse().fail().message("状态不能为空");
            }

            BaseArea queryArea = this.baseAreaService.getOne(new LambdaQueryWrapper<BaseArea>()
                    .eq(BaseArea::getTenantId,baseArea.getTenantId())
                    .eq(BaseArea::getDeletedFlg,FebsConstant.VALID)
                    .eq(BaseArea::getAreaName,baseArea.getAreaName()));
            if(ObjectUtils.isNotEmpty(queryArea)){
                return new FebsResponse().fail().message("区域名称不可重复！");
            }
            baseArea.setCreatedBy(getCurrentUser().getUserName());
            this.baseAreaService.createBaseArea(baseArea);
            return new FebsResponse().success();
        } catch (Exception e) {
            String message = "新增BaseArea失败";
            log.error(message, e);
            throw new FebsException(message);
        }
    }

    /**
     * 逻辑删除 BaseArea
     * @author admin
     * @date 2024-07-31 14:35:47
     */
    @Log("逻辑删除区域信息")
    @GetMapping("baseArea/delete/{id}")
    @ResponseBody
    @RequiresPermissions("baseArea:delete")
    public FebsResponse deleteBaseArea(@PathVariable("id") String baseAreaIds) throws FebsException {
        try {
            BaseArea baseArea = new BaseArea();
            baseArea.setDeletedBy(getCurrentUser().getUserName());
            baseArea.setDeletedTime(new Date());
            baseArea.setDeletedFlg(FebsConstant.INVALID);
            this.baseAreaService.deleteBaseArea(baseArea,baseAreaIds);
            return new FebsResponse().success();
        } catch (Exception e) {
            String message = "删除区域信息失败";
            log.error(message, e);
            throw new FebsException(message);
        }
    }



    /**
     * 修改 区域信息
     * @author admin
     * @date 2024-07-31 14:35:47
     */
    @Log("修改区域信息")
    @PostMapping("baseArea/update")
    @ResponseBody
    @RequiresPermissions("baseArea:edit")
    public FebsResponse updateBaseArea(@RequestBody BaseArea baseArea) throws FebsException {
        try {
            if(StringUtils.isBlank(baseArea.getAreaId())){
                return new FebsResponse().fail().message("区域Id不能为空");
            }
            if(StringUtils.isBlank(baseArea.getAreaName())){
                return new FebsResponse().fail().message("区域名称不能为空");
            }
            if(StringUtils.isBlank(baseArea.getAreaCoordinate())){
                return new FebsResponse().fail().message("位置信息不能为空");
            }
            if(StringUtils.isBlank(baseArea.getAreaType())){
                return new FebsResponse().fail().message("区域类型不能为空");
            }
            if(StringUtils.isBlank(baseArea.getSort())){
                return new FebsResponse().fail().message("排序不能为空");
            }
            if(StringUtils.isBlank(baseArea.getTenantId())){
                return new FebsResponse().fail().message("所属公司不能为空");
            }
            if(StringUtils.isBlank(baseArea.getStatus())){
                return new FebsResponse().fail().message("状态不能为空");
            }
            baseArea.setUpdatedBy(getCurrentUser().getUserName());
            this.baseAreaService.updateBaseArea(baseArea);
            return new FebsResponse().success();
        } catch (Exception e) {
            String message = "修改区域信息失败";
            log.error(message, e);
            throw new FebsException(message);
        }
    }

    /**
     * 修区域商状态
     * @param baseArea
     * @return
     * @throws FebsException
     */
    @Log("修区域状态")
    @PostMapping("baseArea/updateStatus")
    @ResponseBody
    @RequiresPermissions(value={"baseArea:edit"},logical= Logical.OR)
    public FebsResponse updatePostStatus(BaseArea baseArea) throws FebsException {
        try {
            if(StringUtils.isBlank(baseArea.getAreaId())){
                return new FebsResponse().fail().message("区域Id不能为空！");
            }
            if(StringUtils.isBlank(baseArea.getStatus())){
                return new FebsResponse().fail().message("区域状态不能为空！");
            }
            baseArea.setUpdatedBy(getCurrentUser().getUserName());
            baseArea.setUpdatedTime(new Date());

            this.baseAreaService.updateById(baseArea);
            return new FebsResponse().success();
        } catch (Exception e) {
            String message = "修改区域状态失败";
            log.error(message, e);
            throw new FebsException(message);
        }
    }

    /**
     * 删除区域信息检查
     * @author admin
     * @date 2024-07-31 14:35:47
     */
    @Log("删除区域信息检查")
    @GetMapping("baseArea/deleteCheck/{id}")
    @ResponseBody
    @RequiresPermissions("baseArea:delete")
    public FebsResponse deleteCheck(@PathVariable("id") String baseAreaIds) throws FebsException {
        try {
            List<BaseAreaScheduling> schedulingList = schedulingService.list(new LambdaQueryWrapper<BaseAreaScheduling>()
                    .eq(BaseAreaScheduling::getAreaId,baseAreaIds));
            if(CollectionUtils.isEmpty(schedulingList)){
                return new FebsResponse().success().data(true);
            }else {
                return new FebsResponse().success().data(false);
            }

        } catch (Exception e) {
            String message = "删除区域信息检查失败";
            log.error(message, e);
            throw new FebsException(message);
        }
    }

    /**
     * 导出 区域信息的excel
     * @author admin
     * @date 2024-07-31 14:35:47
     */
    @PostMapping("baseArea/excel")
    @ResponseBody
    @RequiresPermissions("baseArea:view")
    public void export(QueryRequest queryRequest, BaseAreDto baseArea, HttpServletResponse response) throws FebsException {
        try {
            List<BaseAreDto> baseAreas = this.baseAreaService.findBaseAreaPage(queryRequest, baseArea).getRecords();
            ExcelKit.$Export(BaseArea.class, response).downXlsx(baseAreas, false);
        } catch (Exception e) {
            String message = "导出Excel失败";
            log.error(message, e);
            throw new FebsException(message);
        }
    }
}
